<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
		<div class="main">
			<div class="main-item goods-list">
				<h2>商品列表</h2>
				<div v-for="(good, index) in goods" :key="good.id">
					<p class="item">{{good.name}}</p>
					<p class="item">￥{{good.price}}</p>
					<button @click="add(index)">加入购物车</button>
				</div>
			</div>
			<div class="main-item cart-list">
				<cart :name="name"></cart>
			</div>
		</div>
  </div>
</template>

<script>
import cart from './components/cart.vue';
import axios from "axios";
// 子组件一般不直接操作父组件数据，所以cart需要改成由父组件发布事件，子组件去订阅事件修改 cart属于子组件数据 
export default {
  name: 'app',
	components: { cart },
	data() {
		return {
			name: '购物车列表',
			goods: []
		}
	},
	async created() {
		const response = await axios.get("/api/goods")
    this.goods = response.data.list
	},
	methods: {
		add(i) {
			const good = this.goods[i]
			this.$bus.$emit('add', good)
		}
	},
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.main{
	display: flex;
}
.main-item{
	width: 50%;
}
.goods-list{
	border-right: 1px solid #ccc;
}
p.item{
	display: inline-block;
	margin-right: 15px;
}
</style>
